package com.fy56.platform.logistics.controller;

import com.fy56.platform.logistics.common.BaseController;
import com.fy56.platform.logistics.model.User;
import com.fy56.platform.logistics.redis.dbutil.TokenConstants;
import com.fy56.platform.logistics.service.common.IRedisService;
import com.fy56.platform.logistics.service.web.IUserService;
import com.fy56.platform.logistics.utils.LogUtils;
import com.fy56.platform.logistics.utils.MD5Util;
import com.fy56.platform.logistics.utils.SessionUtil;
import com.fy56.platform.logistics.utils.UserAgentUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;

/**
 * Created by li on 2018-02-09.
 */
@RestController
@RequestMapping("/")
public class LoginController extends BaseController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRedisService iRedisService;

    @RequestMapping(value = "userLogin", method = RequestMethod.POST)
    public ModelAndView userLogin(User user,HttpServletRequest request, HttpServletResponse response){
        user.setLoginPwd(MD5Util.getMD5Code(user.getLoginPwd()));
        user = iUserService.get(user);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:main.html");
        if (user == null || null == request) {
            modelAndView.setViewName("redirect:index.html?msg=error");
            return modelAndView;
        }

        //生成token
        String token = user.getId() + "-" + UUID.randomUUID().toString().replace("-", "");

        // 设置token到cookie里
        Cookie cookie = new Cookie("token",token);
        cookie.setPath("/");
        cookie.setMaxAge(7200);
        response.addCookie(cookie);

        //存储到redis
        iRedisService.set(String.format(TokenConstants.TOKEN_PREFIX, token),UUID.randomUUID().toString());

        user.setOldLoginIp(user.getLoginIp() == null ? "" : user.getLoginIp());
        user.setOldLoginTime(user.getOldLoginTime() == null ? null : user.getOldLoginTime());
        user.setLoginIp(UserAgentUtils.getRemoteAddr(request));
        user.setLoginTime(new Date());
        iUserService.update(user);
        request.getSession().setAttribute("sessionUser",user);
        LogUtils.saveLog(request,"",user.getId().toString(),user.getId() + "","UserManager","userLogin","用户登陆","");
        return modelAndView;
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:index.html");
        if (null == request) {
            return modelAndView;
        }
        User user = SessionUtil.getSessionUser(request);
        if(null == user){
            return modelAndView;
        }
        Cookie[] cookies = request.getCookies();
        if(null == cookies){
            return modelAndView;
        }
        String token = "";
        for (Cookie cookie : cookies) {
            if("token".equals(cookie.getName())){
                token = cookie.getValue();
            }
            cookie = new Cookie(cookie.getName(),null);
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        if(null != token && !token.isEmpty()){
            //从redis移除
            iRedisService.delete(String.format(TokenConstants.TOKEN_PREFIX, token));
            request.getSession().removeAttribute("sessionUser");
            if(null != user){
                LogUtils.saveLog(request,"",user.getId().toString(),user.getId() + "","UserManager","logout","用户登出","");
            }
        }
        return modelAndView;

    }

}
